#!/bin/sh
#
# chkconfig: 345 13 89
# description: Starts and stops the iSCSI initiator
#
# processname: iscsid
# pidfile: /run/iscsid.pid
# config:  /etc/iscsi/iscsid.conf

# Source function library.
. /etc/init.d/functions

PATH=/sbin:/bin:/usr/sbin:/usr/bin

RETVAL=0

start()
{
	echo -n $"Starting iSCSI initiator service: "
	daemon iscsid
	RETVAL=$?
	success
	echo
	[ $RETVAL -eq 0 ] || return

	touch /run/lock/subsys/open-iscsi

	echo -n $"Setting up iSCSI targets: "
	iscsiadm -m node --loginall=automatic
	success
	echo

}

stop()
{
	echo -n $"Stopping iSCSI initiator service: "
	sync
	iscsiadm -m node --logoutall=all
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		echo "Could not logout from all nodes, try again later"
		return $RETVAL
	fi
	iscsiadm -k 0
	rm -f /run/iscsid.pid
	[ $RETVAL -eq 0 ] && rm -f /run/lock/subsys/open-iscsi
	status=0
	modprobe -r iscsi_tcp 2>/dev/null
	if [ "$?" -ne "0" -a "$?" -ne "1" ]; then
		status=1
	fi
	modprobe -r ib_iser 2>/dev/null
	if [ "$?" -ne "0" -a "$?" -ne "1" ]; then
		status=1
	fi
	if [ "$status" -eq "0" ]; then
		success
	else
		failure
	fi
	echo

}

restart()
{
	stop
	if [ $RETVAL -ne 0 ]; then
		echo "Stopping iSCSI initiator service failed, not starting"
		return $RETVAL
	fi
	start

}

case "$1" in
	start)
			start
			;;
	stop)
			stop
			;;
	restart)
			stop
			if [ $RETVAL -ne 0 ]; then
				echo "Stopping iSCSI initiator service failed, not starting"
				exit $RETVAL
			fi
			start
			;;
	status)
			status iscsid
			RETVAL=$?
			;;
	condrestart)
			[ -f /run/lock/subsys/open-iscsi ] && restart
			;;
	*)
			echo $"Usage: $0 {start|stop|restart|status|condrestart}"
			exit 1
esac

exit $RETVAL
